package redis.inaction.clients.ops;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Slf4j
public class JedisOps extends AbstractOps{

    /**
     * 一般不建议配置 required = false, 此处是演示需要
     */
    @Autowired(required = false)
    private JedisPool jedisPool;

    @Autowired(required = false)
    private JedisCluster jedisCluster;

    @Autowired(required = false)
    private JedisPoolConfig jedisPoolConfig;

    @Autowired
    private ObjectMapper objectMapper;

    public boolean isJedisInitialized(){
        return jedisPool != null || jedisCluster != null;
    }

    public void doSomething() throws JsonProcessingException {
        if( jedisPool != null){
            jedisStandaloneOps();
        }

        if(jedisCluster != null){
            jedisClusterOps();
        }
    }

    protected void jedisStandaloneOps() throws JsonProcessingException {
        log.info("jedis standalone ops:");
        log.info("Jedis Pools Config: {}", objectMapper.writeValueAsString(jedisPoolConfig));
        String hashKey = "jedis_demo";
        try (Jedis jedis = jedisPool.getResource()) {
            redisOps(
                    index -> jedis.hset(hashKey, "k_" + index, "value_" + index),
                    jedis::hgetAll,
                    jedis::hget,
                    hashKey);

        }
    }

    protected void jedisClusterOps() throws JsonProcessingException {
        log.info("jedis cluster ops:");
        log.info("Cluster nodes: {}", jedisCluster.getClusterNodes().toString());
        log.info("Jedis Pools Config: {}", objectMapper.writeValueAsString(jedisPoolConfig));
        String hashKey = "jedis_demo";
        redisOps(
                index -> jedisCluster.hset(hashKey, "k_" + index, "value_" + index),
                jedisCluster::hgetAll,
                jedisCluster::hget,
                hashKey);
    }

}
